package com.dqhl.business.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.business.Base.BaseActivity;
import com.dqhl.business.R;
import com.dqhl.business.adapter.CommunityAdapter;
import com.dqhl.business.modle.Community;
import com.dqhl.business.modle.Residence;
import com.dqhl.business.util.Config;
import com.dqhl.business.util.Constant;
import com.dqhl.business.util.Dlog;
import com.dqhl.business.util.JsonUtils;
import com.dqhl.business.view.CheckableLinearLayout;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * description: 服务范围
 * autour: guanluocang
 * date: 2016/11/8 16:11
 */
public class ServiceAroundActivity extends BaseActivity implements View.OnClickListener {

    private Context context;
    private ImageView iv_goodsGoBack;
    private TextView tv_goodsTopTitle;
    private TextView tv_topRight;
    private ListView lv_range;
    private List<Community> communityList; //所有小区list
    private List<Residence> aroundList;
    private List<Community> communities; //
    private List<String> communityIdList; //
    private List<Community> communitySelectedList; //
    private CommunityAdapter communityAdapter;
    private String strResidence;
    private String[] communityIds;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_around);
        context = this;
        initView();
        initData();
    }

    private void initData() {
        strResidence = getIntent().getStringExtra("residence");
        Dlog.e(strResidence);
        communities = new ArrayList<>();
        communityIdList = new ArrayList<>();
        if (!"[]".equals(strResidence)) {
            aroundList = JSON.parseArray(strResidence, Residence.class);
            for (int i = 0; i < aroundList.size(); i++) {
                Community community = new Community();
                community.setId(aroundList.get(i).getCommunity_id());
                community.setName(aroundList.get(i).getName());
                community.setSelect(true);
                communities.add(community);
                communityIdList.add(community.getId());
            }
        }
        showCustomLoadBar(".");
        RequestParams params = new RequestParams(Config.personal_get_residence);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                if (0 == errCode) {
                    String residence_id = JsonUtils.getInfo(data, "residence_id");
                    communityList = JSON.parseArray(residence_id, Community.class);
//                    communityAdapter.setSelectItem(1);
                    if (communities != null && communities.size() > 0) {
                        for (int i = 0; i < communities.size(); i++) {
//                            Dlog.e("----" + i + "-----");
                            Community community = communities.get(i);
//                            Dlog.e(community.getName() + "+++++");
                            for (int j = 0; j < communityList.size(); j++) {
//                                Dlog.e(j + "");
//                                Dlog.e(community.getId() + "+++++");
//                                Dlog.e(communityList.get(j).getId());
                                if ((communityList.get(j).getId()).equals(community.getId())) {
//                                    Dlog.e(j + "");
//                                    Dlog.e(community.getName() + "+++++");
//                                    Dlog.e(communityList.get(j).getName() + "+++++");
                                    Collections.replaceAll(communityList, communityList.get(j), community);
                                }
                            }
                        }
                    }
                    communityAdapter = new CommunityAdapter(context, communityList);
                    communityAdapter.notifyDataSetChanged();
                    lv_range.setAdapter(communityAdapter);
                    lv_range.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                    lv_range.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Dlog.e("----" + communityList.get(position).getId());
                            CheckableLinearLayout cll = (CheckableLinearLayout) view.findViewById(R.id.layout_community_item);
                            if (cll.isChecked()) {
                                cll.setBackgroundResource(R.drawable.checked_bg);
                                Dlog.e("选择了:" + communityList.get(position).getName());
                                if (!communityIdList.contains(communityList.get(position).getId())) {
                                    communityIdList.add(communityList.get(position).getId());
                                }
//                                communities.add(communityList.get(position));
                            } else {
                                cll.setBackgroundResource(R.drawable.normal_bg);
                                Dlog.e("取消了:" + communityList.get(position).getName());
                                if (communityIdList.contains(communityList.get(position).getId())) {
                                    communityIdList.remove(communityList.get(position).getId());
                                }
//                                communities.remove(communityList.get(position));
                            }
//                            for (int i = 0; i < communities.size(); i++) {
//                                communityIds += communities.get(i).getId() + ",";
//                            }
//                            communityIds = (String[]) communityIdList.toArray();
                            Dlog.e(communityIdList.toString());
//                            doSave(communityList.get(position).getId());
                        }
                    });
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    private void initView() {
        iv_goodsGoBack = (ImageView) findViewById(R.id.iv_goodsGoBack);
        tv_goodsTopTitle = (TextView) findViewById(R.id.tv_goodsTopTitle);
        tv_goodsTopTitle.setText("服务范围");
        tv_topRight = (TextView) findViewById(R.id.tv_topRight);
        tv_topRight.setVisibility(View.VISIBLE);
        tv_topRight.setText("保存");
        lv_range = (ListView) findViewById(R.id.lv_range);

        iv_goodsGoBack.setOnClickListener(this);
        tv_topRight.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_goodsGoBack:
                finish();
                break;
            case R.id.tv_topRight:
                doSave();
                break;
        }
    }

    private void doSave() {
        showCustomLoadBar(".");
//        String community_id = communityIdList.toString().substring(1,communityIdList.toString().length()-1);
        String community_id = communityIdList.toString();
        Dlog.e(user.getUser_id() + ";" + community_id);
        RequestParams params = new RequestParams(Config.personal_range_modify);
        params.addBodyParameter("user_id", user.getUser_id());
        params.addBodyParameter("community_id", community_id);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                if (0 == errCode) {
                    toast("保存成功");
                    sendModifyRangeBroadcast();
                    finish();
                } else {
                    toast("保存失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    private void sendModifyRangeBroadcast() {
        Intent intent = new Intent();
        intent.setAction(Constant.ACTION_UPDATE_RANGE);
        sendBroadcast(intent);
    }

}
